﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Xml.Linq;
using System.Web.UI.HtmlControls;

namespace Framework
{
    public partial class Products : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public List<udv_Categories> allCate = new List<udv_Categories>();
        public List<udv_Articles> allArt = new List<udv_Articles>();
        public List<udv_Products> allPro = new List<udv_Products>();

        public List<udv_Products> lstProduct = new List<udv_Products>();
        public List<udv_Categories> lstCate = new List<udv_Categories>();

        protected void Page_Load(object sender, EventArgs e)
        {
            Form.DefaultButton = btnSearch.UniqueID;

            if (!IsPostBack)
            {
                txtSearch.Attributes["placeholder"] = Globals.GetLanguage("Nhập tìm kiếm ở đây", "Enter search here", true);
                LoadCacheCategory();
                LoadCacheArticle();
                LoadCacheProduct();

                LoadProducts();
            }
        }

        public void LoadCacheCategory()
        {
            if (Cache["Category"] == null)
            {
                Cache["Category"] = allCate = entity.udv_Categories.ToList();
            }
            else
            {
                allCate = (List<udv_Categories>)Cache["Category"];
            }
        }

        public void LoadCacheArticle()
        {
            if (Cache["Article"] == null)
            {
                Cache["Article"] = allArt = entity.udv_Articles.Include("udv_Categories").ToList();
            }
            else
            {
                allArt = (List<udv_Articles>)Cache["Article"];
            }
        }

        public void LoadCacheProduct()
        {
            if (Cache["Product"] == null)
            {
                Cache["Product"] = allPro = entity.udv_Products.Include("udv_Categories").Include("udv_ProductComments").ToList();
            }
            else
            {
                allPro = (List<udv_Products>)Cache["Product"];
            }
        }

        public string GetDefaultTitlePage()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("Title").Value.Trim();
        }

        public string GetDefaultMetaDescription()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaDescription").Value.Trim();
        }

        public string GetDefaultMetaKeyword()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaKeywords").Value.Trim();
        }

        public string GetDefaultMetaTitle()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaTitle").Value.Trim();
        }

        public void AddTag(string metaDescription, string metaKeywords, string metaTitle, string pageTitle)
        {
            if (string.IsNullOrEmpty(metaDescription))
            {
                metaDescription = GetDefaultMetaDescription();
            }
            if (string.IsNullOrEmpty(metaKeywords))
            {
                metaKeywords = GetDefaultMetaKeyword();
            }
            if (string.IsNullOrEmpty(pageTitle))
            {
                pageTitle = GetDefaultTitlePage();
            }
            if (string.IsNullOrEmpty(metaTitle))
            {
                metaTitle = GetDefaultMetaTitle();
            }
            HtmlHead headTag = (HtmlHead)this.Master.FindControl("Head1");
            headTag.Title = pageTitle;
            HtmlMeta PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "description";
            PagemetaTag.Content = metaDescription;
            headTag.Controls.AddAt(2, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "keywords";
            PagemetaTag.Content = metaKeywords;
            headTag.Controls.AddAt(3, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "title";
            PagemetaTag.Content = metaTitle;
            headTag.Controls.AddAt(4, PagemetaTag);
        }

        public void LoadPaging(List<int> allBox, ref Controls_PagingControl PagingControl, ref Repeater rpControl, udv_Categories cate, int pageSize)
        {
            double NOProducts = 0;

            PagingControl.pageUrl = ResolveUrl("~/" + DGSFramework.Globals.GetUrl(cate.UrlRewrite, DGSFramework.Globals.GetUrlAspx(cate.UrlRewrite, true) + cate.CateID));

            object objPage = Request.QueryString["page"];
            // check paging
            if (objPage != null)
            {
                int pageindex;
                if (int.TryParse(objPage.ToString(), out pageindex))
                {
                    PagingControl.PageIndex = pageindex;
                }
            }
            else
                PagingControl.PageIndex = 1;

            // check exp must exist
            if (allBox.Count() == 0)
            {
                return;
            }
            // cal paging
            NOProducts = (double)allBox.Count() / pageSize;
            char splitChar = '.';

            if (NOProducts.ToString().Contains('.'))
            { NOProducts++; splitChar = '.'; }

            if (NOProducts.ToString().Contains(','))
            { NOProducts++; splitChar = ','; }

            PagingControl.TotalPage = int.Parse(NOProducts.ToString().Split(splitChar).GetValue(0).ToString());

            if (PagingControl.TotalPage <= 1)
                PagingControl.Visible = false;
            else
                PagingControl.Visible = true;

            allBox = allBox.Count() <= pageSize ? allBox : allBox
                .Skip((PagingControl.PageIndex - 1) * pageSize).Take(pageSize).ToList();
            rpControl.DataSource = allBox;
            rpControl.DataBind();
        }

        public void LoadProducts()
        {
            if (Request.QueryString["CateID"] != null)
            {
                int cateID;
                int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
                var cateCurrent = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
                if (cateCurrent == null)
                {
                    Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
                }
                else
                {
                    //string strUrlOriginal = ConfigPaths.Domain_Url + Globals.GetUrl(cateCurrent.UrlRewrite, Globals.GetUrlAspx(cateCurrent.UrlRewrite, true) + cateCurrent.CateID);
                    //if (CheckUrlOriginal(strUrlOriginal) == false)
                    //{
                    //    Response.Redirect(strUrlOriginal);
                    //}

                    LoadCateLevel(cateCurrent);

                    ltrCateTitle.Text = Globals.GetLanguage(cateCurrent.Title, cateCurrent.Title_en, true);

                    List<udv_Categories> lstCateSub = allCate.Where(ca => ca.ParentID == cateCurrent.CateID && ca.IsActive == true).ToList();
                    if (lstCateSub.Count > 1)
                    {
                        lstCate = lstCateSub.OrderBy(ca => ca.DisplayOrder).ThenByDescending(ca => ca.AddedDate).ToList();
                        Controls_PagingControl pagingControl = (Controls_PagingControl)PagingControl1;
                        //LoadPaging(cateChilds, ref pagingControl, ref rpCateSub, cateCurrent, cateCurrent.PagingSize.Value);
                        
                        
                        //tong so san pham
                        int countProChilds = lstCate.Count();
                        if (countProChilds == 1)
                        {
                            Response.Redirect(ResolveUrl("~/" + Globals.GetUrl(lstCate.FirstOrDefault().UrlRewrite, Globals.GetUrlAspx(lstCate.FirstOrDefault().UrlRewrite, true) + lstCate.FirstOrDefault().CateID)));
                        }
                        //so box tren 1 trang. Qui doi so san pham tren 1 trang thanh so box tren 1 trang
                        int boxPerPage = 0;
                        //tong so box
                        int allBox = 0;
                        //So san pham tren 1 trang
                        int productPerPage = cateCurrent.PagingSize.Value;
                        List<int> allBoxInPage = new List<int>();
                        if (productPerPage % 3 == 0)
                        {
                            boxPerPage = productPerPage / 3;
                        }
                        else
                        {
                            boxPerPage = productPerPage / 3 + 1;
                        }
                        allBox = (countProChilds * boxPerPage) % cateCurrent.PagingSize.Value > 0 ? ((countProChilds * boxPerPage) / cateCurrent.PagingSize.Value) + 1 : (countProChilds * boxPerPage) / cateCurrent.PagingSize.Value;
                        for (int i = 0; i < allBox; i++)
                        {
                            allBoxInPage.Add(i);
                        }
                        LoadPaging(allBoxInPage, ref pagingControl, ref rpCate, cateCurrent, cateCurrent.PagingSize.Value);
                    }
                    else
                    {
                        List<udv_Categories> lstCateProduct = Globals.LoopGetCategories(ref allCate, cateCurrent.CateID);
                        lstCateProduct.Add(allCate.Where(ca => ca.CateID == cateCurrent.CateID).FirstOrDefault());
                        foreach (var item in lstCateProduct)
                        {
                            lstProduct = lstProduct.Union(allPro
                                .Where(pr => pr.udv_Categories.CateID == item.CateID && pr.IsActive == true)
                                .OrderBy(pr => pr.DisplayOrder)
                                .ThenByDescending(pr => pr.AddedDate)).ToList();
                        }

                        lstProduct = lstProduct
                            .OrderBy(pr => pr.DisplayOrder)
                            .ThenByDescending(pr => pr.AddedDate).ToList();

                        Controls_PagingControl pagingControl = (Controls_PagingControl)PagingControl1;
                        //tong so san pham
                        int countProChilds = lstProduct.Count();
                        if (countProChilds == 1)
                        {
                            Response.Redirect(ResolveUrl("~/" + Globals.GetUrl(lstProduct.FirstOrDefault().UrlRewrite, Globals.GetUrlAspx(lstProduct.FirstOrDefault().UrlRewrite, false) + lstProduct.FirstOrDefault().ProductID)));
                        }
                        //so box tren 1 trang. Qui doi so san pham tren 1 trang thanh so box tren 1 trang
                        int boxPerPage = 0;
                        //tong so box
                        int allBox = 0;
                        //So san pham tren 1 trang
                        int productPerPage = cateCurrent.PagingSize.Value;
                        List<int> allBoxInPage = new List<int>();
                        if (productPerPage % 3 == 0)
                        {
                            boxPerPage = productPerPage / 3;
                        }
                        else
                        {
                            boxPerPage = productPerPage / 3 + 1;
                        }
                        allBox = (countProChilds * boxPerPage) % cateCurrent.PagingSize.Value > 0 ? ((countProChilds * boxPerPage) / cateCurrent.PagingSize.Value) + 1 : (countProChilds * boxPerPage) / cateCurrent.PagingSize.Value;
                        for (int i = 0; i < allBox; i++)
                        {
                            allBoxInPage.Add(i);
                        }
                        LoadPaging(allBoxInPage, ref pagingControl, ref rpProduct, cateCurrent, boxPerPage);
                    }
                    LoadBreadcrumb(cateCurrent.CateID, ref rpBreadcrumb);
                    AddTag(cateCurrent.MetaDescription,
                            cateCurrent.MetaKeywords,
                            !string.IsNullOrEmpty(cateCurrent.MetaTitle) ? cateCurrent.MetaTitle : cateCurrent.Title,
                            Globals.GetLanguage(cateCurrent.Title, cateCurrent.Title_en, true));
                    if (!string.IsNullOrEmpty(cateCurrent.MetaOrther))
                    {
                        ltrMetaOrther.Text = cateCurrent.MetaOrther;
                    }
                }
            }
            else
            {
                Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
            }
        }

        public bool CheckUrlOriginal(string urlOriginal)
        {
            string strUrlOriginal = urlOriginal.Substring(0, urlOriginal.ToLower().IndexOf(".html"));
            string strUrlRequest = ConfigPaths.Domain_Url.Substring(0, ConfigPaths.Domain_Url.Length - 1) + (Request.ServerVariables["HTTP_X_REWRITE_URL"] != null ? Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString() : Request.RawUrl);
            if (strUrlRequest.ToLower().Trim().Contains(strUrlOriginal))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void LoadCateLevel(udv_Categories cateCurrent)
        {
            List<udv_Categories> lstCateLevel = allCate
                .Where(ca => ca.IsActive == true && ca.ParentID == cateCurrent.CateID).ToList();
            ltrParentCate.Text = Globals.GetLanguage(cateCurrent.Title, cateCurrent.Title_en, true);
            if (lstCateLevel.Count == 0)
            {
                lstCateLevel = allCate
                .Where(ca => ca.IsActive == true && ca.ParentID == cateCurrent.ParentID).ToList();
                udv_Categories cateParent = allCate.Where(ca => ca.CateID == cateCurrent.ParentID).FirstOrDefault();
                if (cateParent.CateID != ConfigPaths.Category_Article_ID && cateParent.CateID != ConfigPaths.Category_Product_ID)
                {
                    ltrParentCate.Text = Globals.GetLanguage(cateParent.Title, cateParent.Title_en, true);
                }
            }
            rpCateLevel.DataSource = lstCateLevel;
            rpCateLevel.DataBind();
        }

        public void LoadBreadcrumb(int cateID, ref Repeater rpBreadcrumb)
        {
            List<udv_Categories> allCateChild = new List<udv_Categories>();
            LoopCategoryChild(ref allCateChild, cateID);
            allCateChild.RemoveAt(0);
            if (allCateChild.Count > 0)
            {
                allCateChild.RemoveAt(allCateChild.Count - 1);
            }
            rpBreadcrumb.DataSource = allCateChild;
            rpBreadcrumb.DataBind();
        }

        public void LoopCategoryChild(ref List<udv_Categories> allCateChild, int cateID)
        {
            udv_Categories cate = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
            if (cate != null)
            {
                allCateChild.Insert(0, cate);
                LoopCategoryChild(ref allCateChild, cate.ParentID.Value);
            }
        }

        protected void rpCate_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int cateID;
            int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
            var cateCurrent = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
            int page = 1;
            if (Request.QueryString["page"] != null)
            {
                try
                {
                    page = int.Parse(Request.QueryString["page"]);
                }
                catch
                {
                    page = 1;
                }
            }
            Repeater rpCateSub = (Repeater)e.Item.FindControl("rpCateSub");
            var lstCateChilds = lstCate.OrderBy(pr => pr.DisplayOrder).ThenByDescending(pr => pr.AddedDate)
                .Skip(e.Item.ItemIndex * 3 + cateCurrent.PagingSize.Value * (page - 1))
                .Take(3 * (e.Item.ItemIndex + 1) <= cateCurrent.PagingSize.Value ? 3 : cateCurrent.PagingSize.Value - (3 * e.Item.ItemIndex)).ToList();
            rpCateSub.DataSource = lstCateChilds;
            rpCateSub.DataBind();
        }

        protected void rpProduct_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int cateID;
            int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
            var cateCurrent = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
            int page = 1;
            if (Request.QueryString["page"] != null)
            {
                try
                {
                    page = int.Parse(Request.QueryString["page"]);
                }
                catch
                {
                    page = 1;
                }
            }
            Repeater rpProductSub = (Repeater)e.Item.FindControl("rpProductSub");
            var lstProductChilds = lstProduct.OrderBy(pr => pr.DisplayOrder).ThenByDescending(pr => pr.AddedDate)
                .Skip(e.Item.ItemIndex * 3 + cateCurrent.PagingSize.Value * (page - 1))
                .Take(3 * (e.Item.ItemIndex + 1) <= cateCurrent.PagingSize.Value ? 3 : cateCurrent.PagingSize.Value - (3 * e.Item.ItemIndex)).ToList();
            rpProductSub.DataSource = lstProductChilds;
            rpProductSub.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string textSearch = txtSearch.Text.Trim();
            Response.Redirect(ResolveUrl("~/" + DGSFramework.Globals.GetUrl("tim-kiem-san-pham/" + Server.UrlEncode(textSearch), "SearchProduct.aspx?Keyword=" + Server.UrlEncode(textSearch))));
        }
    }
}